package cn.modfun.common.file;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.util.Map;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

import cn.modfun.common.lang.ChainMap;


public class QiniuOSSUploadUtils extends OSSUpload {

	private String access_key;
	
	private String secret_key;
	
	private String bucket;
	
	private Zone zone = Zone.autoZone();
	/**
	 * 静态实例化对象
	 */
	public static QiniuOSSUploadUtils instantiation = new QiniuOSSUploadUtils();

	public QiniuOSSUploadUtils setAccessKey(String access_key) {
		this.access_key = access_key;
		return this;
	}

	public QiniuOSSUploadUtils setSecretKey(String secret_key) {
		this.secret_key = secret_key;
		return this;
	}

	public QiniuOSSUploadUtils setBucket(String bucket) {
		this.bucket = bucket;
		return this;
	}

	public QiniuOSSUploadUtils setZone(Zone zone) {
		this.zone = zone;
		return this;
	}

	public QiniuOSSUploadUtils(){}
	
	/**
	 * 
	 * @param access_key
	 * @param secret_key
	 * @param bucket
	 */
	public QiniuOSSUploadUtils(String access_key,String secret_key,String bucket){
		this.access_key = access_key;
		this.secret_key = secret_key;
		this.bucket = bucket;
	}

	@Override
	public Map<String, Object> upload(String file_name) {
		File file = new File(file_name);
		if(file.exists() && file.isFile()){
			return upload(file);
		}
		return null;
	}

	@Override
	public Map<String, Object> upload(File file) {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			return uploadByInputStream(fis);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			closeFileInputStream(fis);
		}
		return null;
	}

	@Override
	public Map<String, Object> upload(String file_name, String limit_mode, String[] file_suffix, Long limit_size) throws Exception {
		File file = new File(file_name);
		if(file.exists() && file.isFile()){
			return upload(file, limit_mode, file_suffix, limit_size);
		}
		return null;
	}

	@Override
	public Map<String, Object> upload(File file, String limit_mode, String[] file_suffix, Long limit_size) throws Exception {
		FileChannel fc = null;
		FileInputStream fis = null;
		Map<String,Object> map = null;
		try {
			fis = new FileInputStream(file);
			fc= fis.getChannel();
			LimitMessage limit = limit(file.getName(),fc.size(), limit_mode, file_suffix, limit_size);
			if(!limit.isSuccess()){
				closeFileChannel(fc);
				closeFileInputStream(fis);
				throw new Exception(limit.getMessage());
			}
			return uploadByInputStream(fis);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			closeFileChannel(fc);
			closeFileInputStream(fis);
		}
		return map;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String,Object> uploadByInputStream(InputStream is){
		/**
		 * 定义配置
		 */
		Configuration cfg = new Configuration(zone);
		UploadManager uploadManager = new UploadManager(cfg);
		/**
		 * 设置策略
		 */
		StringMap policy = new StringMap();
		policy.put("returnBody", new Gson().toJson(new ChainMap().put("file_name", "$(key)").put("etag", "$(etag)").put("bucket", "$(bucket)").put("file_size", "$(fsize)").put("file_original_name", "${fname}").put("file_mime_type", "${mimeType}").put("file_suffix", "${ext}")));
		/* 上传过期时间 */
		long expireSeconds = 3600;
		try {
		    Auth auth = Auth.create(access_key, secret_key);
			String upToken = auth.uploadToken(bucket, null, expireSeconds, policy);
		    try {
		        Response response = uploadManager.put(toByteArray(is), null, upToken);
		        closeInputStream(is);
		        //解析上传成功的结果
		        return new Gson().fromJson(response.bodyString(), Map.class);
		    } catch (QiniuException ex) {
		    	closeInputStream(is);
		        Response r = ex.response;
		        System.err.println(r.toString());
		        try {
		            System.err.println(r.bodyString());
		        } catch (QiniuException ex2) {
		            //ignore
		        }
		    }
		} catch (Exception ex) {
		    //ignore
		}
		return null;
	}
	
	public static void main(String[] args) {
		String ACCESS_KEY = "C265m-GWsnt0O4GVy1P6ZJYlftENXsoy1jb-WqqR";
		String SECRET_KEY = "oGk4Cg2e5cJJHrDjy3pChfe-Slus1dep9IRoRNpx";
		String BUCKET = "dangxuejiaoyu";
		
		QiniuOSSUploadUtils uu = new QiniuOSSUploadUtils(ACCESS_KEY,SECRET_KEY,BUCKET);
		try {
			System.out.println(uu.upload("e://weixin.jpg", "exclude", new String[]{".exe"}, 11111l));;
		} catch (Exception e) {
			e.printStackTrace();
		}
		//System.out.println(instantiation.setAccessKey(ACCESS_KEY).setBucket(BUCKET).setSecretKey(SECRET_KEY).upload("e://weixin.jpg"));
	}
}
